package com.ruoyi.monitor.utils.Common.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.monitor.Vo.PredictDataVo;
import com.ruoyi.monitor.domain.AutoSendTask;
import com.ruoyi.monitor.domain.Pollutant;
import com.ruoyi.monitor.domain.SysMsg;
import com.ruoyi.monitor.service.IAutoSendTaskService;
import com.ruoyi.monitor.service.ISysMsgService;
import com.ruoyi.monitor.utils.Common.DateUtils;
import com.ruoyi.monitor.utils.Email.Mail;
import com.ruoyi.monitor.utils.Email.MailCenter;
import com.ruoyi.monitor.utils.Msg.Message;
import com.ruoyi.monitor.utils.Msg.MsgUtil;
import com.ruoyi.monitor.utils.Msg.SMSCenter;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component("sender")
public class CommonSender {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysMsgService msgService;
    @Autowired
    private MailCenter mailCenter;
    @Autowired
    private MsgUtil msgUtil;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IAutoSendTaskService autoSendTaskService;
    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    ThreadPoolTaskExecutor pool;
    private Boolean f;

    /**
     * 定时发送的方法，勿删
     * @param jobId
     */
    public void sendTo(Integer jobId){
        List<AutoSendTask> tasks = autoSendTaskService.selectTasksByJobId(Long.valueOf(jobId));
        tasks.forEach(task->{
            pool.submit(()->{
                SysUser user = sysUserService.selectUserById(task.getUserId());
                SysMsg sysMsg = new SysMsg();
                sysMsg.setType(Mail.TYPE_EMAIL);
                sysMsg.setDate(new Date());
                sysMsg.setRank("定时发送");
                sysMsg.setUser(user);
                sysMsg.setContent("用户"+user.getUserName()+","+task.getContent());
                sysMsg.setTitle(task.getTitle());
                if (!ObjectUtil.isEmpty(task.getModelId())) sysMsg.setModelId(task.getModelId());
                sysMsg.setTaskId(task.getId());
                mailCenter.sendTo(user,sysMsg);
            });
        });
    }


    public void sendAll(List<Pollutant> pollutants){
        String flag = redisCache.getCacheObject("preInfo");
        if (ObjectUtil.isEmpty(flag)){
            this.f = true;
            redisCache.setCacheObject("preInfo","0");
        }else {
            if ("0".equals(flag)) this.f = true;
            else this.f = false;
        }
        if (pollutants.size() == 1){
            Pollutant pollutant = pollutants.get(0);

            bySMS(pollutant);
            byMail(pollutant);
        }else {
            Pollutant now = pollutants.get(pollutants.size() - 1);
            String mark = UUID.randomUUID().toString()+now.getAreaCode();
            Pollutant past = pollutants.get(pollutants.size() - 2);
            String suggest = msgUtil.getSuggest(now);
            List<SysUser> users = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getStatus, Message.ON)
                    .eq(SysUser::getMsgStatus, Message.ON));

            users.forEach(user -> {
                SysMsg msg = new SysMsg();
                msg.setRank(mark);
                String content = msgUtil.warnMessage(user,now,past,suggest);
                if (this.f){
                    PredictDataVo dataVo = redisCache.getCacheObject("pre24");
                    if (!ObjectUtil.isEmpty(dataVo)){
                        String[] dates = dataVo.getDates();
                        for (int i = 0; i < dates.length; i++) {
                            Date trans = DateUtils.trans(dates[i]);
                            if (trans.after(new Date())){
                                content += msgUtil.preForHours(dataVo,i);
                                break;
                            }else {
                                if (i==dates.length-1){
                                    System.out.println("不是最新数据");
                                }
                            }
                        }
                    }
                }
                if (now.getAqi()<100){
                    msg.setTitle(Message.TIP_TITLE);
                }else {
                    msg.setTitle(Message.WARN_TITLE);
                }
                msg.setContent(content);
                msg.setUserId(user.getUserId());
                msg.setDate(new Date());
                msg.setType(Message.TYPE_MESSAGE);

                msgService.save(msg);
            });

            List<SysUser> users2 = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                    .eq(SysUser::getStatus, Message.ON)
                    .eq(SysUser::getMailStatus, Mail.ON));
            users2.forEach(user2 -> {
                SysMsg msg = new SysMsg();
                msg.setRank(mark);
                String content = msgUtil.warnMessage(user2, now,past, suggest);
                if (this.f){
                    PredictDataVo dataVo = redisCache.getCacheObject("pre24");
                    if (!ObjectUtil.isEmpty(dataVo)){
                        String[] dates = dataVo.getDates();
                        for (int i = 0; i < dates.length; i++) {
                            Date trans = DateUtils.trans(dates[i]);
                            if (trans.after(new Date())){
                                content += msgUtil.preForHours(dataVo,i);
                                break;
                            }else {
                                if (i==dates.length-1){
                                    System.out.println("不是最新数据");
                                }
                            }
                        }
                    }
                }
                if (now.getAqi()<100){
                    msg.setTitle(Message.TIP_TITLE);
                }else {
                    msg.setTitle(Message.WARN_TITLE);
                }
                if (this.f){
                    PredictDataVo dataVo = redisCache.getCacheObject("pre24");
                    if (!ObjectUtil.isEmpty(dataVo)){
                        String[] dates = dataVo.getDates();
                        for (int i = 0; i < dates.length; i++) {
                            Date trans = DateUtils.trans(dates[i]);
                            if (trans.after(new Date())){
                                content += msgUtil.preForHours(dataVo,i);
                                break;
                            }else {
                                if (i==dates.length-1){
                                    System.out.println("不是最新数据");
                                }
                            }
                        }
                    }
                }
                msg.setContent(content);
                msg.setUserId(user2.getUserId());
                msg.setDate(new Date());
                msg.setType(Mail.TYPE_EMAIL);

                mailCenter.sendTo(user2,msg);
                msgService.save(msg);
            });

        }
    }

    public void bySMS(Pollutant pollutant){
        String mark = UUID.randomUUID().toString()+pollutant.getAreaCode();
        String suggest = msgUtil.getSuggest(pollutant);
        List<SysUser> users = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getStatus, Message.ON)
                .eq(SysUser::getMsgStatus, Message.ON));
        users.forEach(user -> {
            SysMsg msg = new SysMsg();
            msg.setRank(mark);
            String content = msgUtil.warnMessage(user, pollutant, suggest);
            System.out.println(content);
            if (pollutant.getAqi()<100){
                msg.setTitle(Message.TIP_TITLE);
            }else {
                msg.setTitle(Message.WARN_TITLE);
            }
            if (this.f){
                PredictDataVo dataVo = redisCache.getCacheObject("pre24");
                if (!ObjectUtil.isEmpty(dataVo)){
                    String[] dates = dataVo.getDates();
                    for (int i = 0; i < dates.length; i++) {
                        Date trans = DateUtils.trans(dates[i]);
                        if (trans.after(new Date())){
                            content += msgUtil.preForHours(dataVo,i);
                            break;
                        }else {
                            if (i==dates.length-1){
                                System.out.println("不是最新数据");
                            }
                        }
                    }
                }
            }
            msg.setContent(content);
            msg.setUserId(user.getUserId());
            msg.setDate(new Date());
            msg.setType(Message.TYPE_MESSAGE);
            msgService.save(msg);
        });
    }

    public void byMail(Pollutant pollutant){
        String mark = UUID.randomUUID().toString()+pollutant.getAreaCode();
        String suggest = msgUtil.getSuggest(pollutant);
        List<SysUser> users = sysUserService.list(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getStatus, Message.ON)
                .eq(SysUser::getMailStatus, Mail.ON));
        users.forEach(user -> {
            SysMsg msg = new SysMsg();
            msg.setRank(mark);

            String content = msgUtil.warnMessage(user, pollutant, suggest);
            if (pollutant.getAqi()<100){
                msg.setTitle(Message.TIP_TITLE);
            }else {
                msg.setTitle(Message.WARN_TITLE);
            }
            if (this.f){
                PredictDataVo dataVo = redisCache.getCacheObject("pre24");
                if (!ObjectUtil.isEmpty(dataVo)){
                    String[] dates = dataVo.getDates();
                    for (int i = 0; i < dates.length; i++) {
                        Date trans = DateUtils.trans(dates[i]);
                        if (trans.after(new Date())){
                            content += msgUtil.preForHours(dataVo,i);
                            break;
                        }else {
                            if (i==dates.length-1){
                                System.out.println("当前预测数据，不是最新，不发送");
                            }
                        }
                    }
                }
            }
            msg.setContent(content);
            msg.setUserId(user.getUserId());
            msg.setDate(new Date());
            msg.setType(Mail.TYPE_EMAIL);
            mailCenter.sendTo(user,msg);
            System.out.println(msg);
            msgService.save(msg);
        });
    }

}
